package com.young.rpc;

import com.young.scheduler.grpc.VClientSheduleServiceGrpc;
import io.grpc.Server;
import io.grpc.netty.NettyServerBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @description：
 * @author: yangyahui01
 * @date: 12/3/24 11:21 AM
 */
public class ServerBootStrap {
    private static final Logger LOGGER = LoggerFactory.getLogger(ServerBootStrap.class);

    private VClientSheduleServiceGrpc.VClientSheduleServiceImplBase clientScheduleService;

    private Server server;

    private int port = 50091;

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    public void setClientScheduleService(VClientSheduleServiceGrpc.VClientSheduleServiceImplBase clientScheduleService) {
        this.clientScheduleService = clientScheduleService;
    }

    public VClientSheduleServiceGrpc.VClientSheduleServiceImplBase getClientScheduleService() {
        return clientScheduleService;
    }

    public void start() throws Exception {

        server = NettyServerBuilder.forPort(port).addService(clientScheduleService)
                .build().start();

        LOGGER.info("Server started, listening on {}", port);

        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                LOGGER.info("*** shutting down gRPC server since JVM is shutting down");
                ServerBootStrap.this.stop();
                LOGGER.info("*** server shut down");
            }
        });
    }

    public void stop() {
        if (server != null) {
            server.shutdown();
        }
    }

    /**
     * Await termination on the main thread since the grpc library uses daemon threads.
     */
    private void blockUntilShutdown() throws InterruptedException {
        if (server != null) {
            server.awaitTermination();
        }
    }

    public static void main(String[] args) {
        final ServerBootStrap server = new ServerBootStrap();
        try {
            server.start();
            server.blockUntilShutdown();
        } catch (Exception e) {
            LOGGER.error("启动失败", e);
        }

    }

    public void init() throws Exception {
        LOGGER.info("开始启动ServerBootStrap......");
        start();
    }

}
